﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using RestSharp;
using SqlSugar;
using StackExchange.Profiling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MyApp.WebApi.Extensions
{
    public static class IocServiceSetup
    {
        /// <summary>
        /// NetCore自带容器中注入
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static void AddIocSetup(this IServiceCollection services)
        {
            #region 单个注入
            //services.AddScoped<IInterfaceToolRepository, InterfaceToolRepository>();
            //services.AddScoped<IInterfaceToolService, InterfaceToolService>(); 
            #endregion

            #region 依赖注入

            var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
            var referencedAssemblies = System.IO.Directory.GetFiles(path, "MyAPP*.dll").Where(c=>c.Contains("Repository")||c.Contains("Service")).Select(Assembly.LoadFrom).ToArray();
            var types = referencedAssemblies
                .SelectMany(a => a.DefinedTypes)
                .Select(type => type.AsType())
                .Where(t =>t.Name.Contains("Repository")||t.Name.Contains("Service")).ToArray();
            var implementTypes = types.Where(x => x.IsClass).ToArray();
            var interfaceTypes = types.Where(x => x.IsInterface).ToArray();
            foreach (var implementType in implementTypes)
            {
                var interfaceType = interfaceTypes.FirstOrDefault(x => x.IsAssignableFrom(implementType));
                if (interfaceType != null)
                    services.AddScoped(interfaceType, implementType);
            }

            #endregion
 
        }
    }
}
